package com.at.controller;

import com.at.domain.Comment;
import com.at.domain.User;
import com.at.service.BlogService;
import com.at.service.CommentServce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author : code1997
 * @date :2020-10-2020/10/16 20:26
 */
@Controller
public class CommentController {

    @Autowired
    private CommentServce commentServce;

    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){

        model.addAttribute("comments", commentServce.listCommentByBlogId(blogId));
        return "blog::commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session){
        User user =(User) session.getAttribute("user");
        Long blogId=comment.getBlog().getId();
        comment.setBlog(blogService.getBolg(blogId));
        if (user!=null){
            //当前用户登陆了，是管理员，就从session中获取信息，并声明为管理员用户
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        }else {
            comment.setAvatar(avatar);
        }
        commentServce.saveComment(comment);
        return "redirect:/comments/"+comment.getBlog().getId();
    }
}
